package com.example.mqttxprovider.callback;

import javax.annotation.Resource;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.example.mqttxprovider.entity.Message;
import com.example.mqttxprovider.service.MessageTreeService;

@Component
public class MqttConsumerCallBack implements MqttCallback {

    private static final Logger log = LoggerFactory.getLogger(MqttConsumerCallBack.class);

    @Autowired
    private MessageTreeService messageTreeService;

    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，可重连");
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        try {
            int qos = mqttMessage.getQos();
            byte[] payload = mqttMessage.getPayload();
            Double value = Double.valueOf(new String(payload));
            System.out.println(String.format("接收消息主题 : %s",topic));
            System.out.println(String.format("接收消息Qos : %d",qos));
            System.out.println(String.format("接收消息内容 : %s",new String(payload)));
            System.out.println(String.format("接收消息retained : %b",mqttMessage.isRetained()));
            Message message = new Message();
            message.setCreateTime(System.currentTimeMillis());
            message.setType(topic);
            message.setValue(value.intValue());
            messageTreeService.save(message);
        }catch (Exception e){
            e.printStackTrace();
            log.error("接受消息错误", e);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println(String.format("接收消息成功"));
    }

}
